<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Order extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->library('form_validation');
		$this->load->library('email');
		$this->load->helper('url');
		$this->load->model('Produk_model');
		$this->load->model('Member_model');
		$this->load->helper('bantuan_helper');
		$this->load->model('Order_model');

	}

	function index()
	{

		$session_id = $this->session->userdata('session_id');
		$data['num_cart'] = $this->Order_model->getCart($session_id,FALSE,TRUE);
		$data['cart'] = $this->Order_model->getCart($session_id);
		$data['ses_id'] = $this->session->userdata('session_id');
		$sql =$this->db->query("SELECT SUM(temp_jml) as tot_temp,SUM(temp_subtotal) as tot_subtotal
							FROM tb_temp_cart
							WHERE session_id = '$session_id'");
		$data['cumb'] = anchor('home','<strong>Home</strong>').' &raquo; Cart';	
		$data['total']=$sql->row('tot_subtotal');
		
		// QUERY GET FAVORITE PRODUK
		
		$qr_fav = $this->db->query('
			SELECT 
			pr.produk_id,
			pr.nama_produk,
			pr.prod_brand_id,
			pr.harga,
			pr.persen_diskon,
			pr.prod_kat_id,
			pr.deskripsi,
			img.produk_img_thumb,
			count(pr.produk_id) AS count_pr
			FROM tb_wishlist ws
			INNER JOIN tb_produk pr ON pr.produk_id = ws.produk_id
			INNER JOIN tb_image_produk img ON img.image_produk_id = ws.produk_id
			WHERE img.look = 1
			GROUP BY pr.produk_id
			ORDER BY count_pr DESC LIMIT 4
		');
		$data['arr_produk_fav'] = $qr_fav->result_array();
		
		
		$data['main_view'] = 'slak/order/order_cart';
		$data['title'] = 'home';
		$data['page'] = 'common';
		$this->load->view('/slak/index',$data);
	}

	function add_cart(){

		$this->form_validation->set_rules('jml', 'Jumlah', 'required');
        $this->form_validation->set_rules('size_produk_id', 'Size', 'required');
		
		
		if ($this->form_validation->run() == FALSE)
		{
			$id_brand = $this->input->post('id_brand');
                        $id_prod = $this->input->post('id_prod');
                        $id_kat = $this->input->post('id_kat');
                        $slug = $this->input->post('slug');
	
			redirect('produk/view/'.$id_brand.'/'.$id_kat.'/'.$id_prod.'/'.$slug,'refresh');
		}
		else
		{
			
			$session_id = $this->session->userdata('session_id');
			$id_brand = $this->input->post('id_brand');
                        $id_prod = $this->input->post('id_prod');
                        $id_kat = $this->input->post('id_kat');
                        $slug = $this->input->post('slug');
			
			if((!empty($id_prod))&& (!empty($session_id))) {
				$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
				$this->form_validation->set_rules('jml', 'Jumlah', 'trim|required');
				if ($this->form_validation->run() == FALSE) {
					redirect('produk/view/'.$id_brand.'/'.$id_kat.'/'.$id_prod.'/'.$slug,'refresh');
				}
				else 
				{
                                        
			
					$jml = mysql_escape_string($this->input->post('jml'));
                    $size_id = mysql_escape_string($this->input->post('size_produk_id'));
					$prod = $this->Produk_model->getProductById($id_prod,$size_id);
					$jml_stok = $prod->jml_item;
					$harga = $prod->harga;
					$disc = $prod->persen_diskon;
					$itung = $jml_stok - $jml;
					if ($itung<0)
					{
                        $id_brand = $this->input->post('id_brand');
                        $id_prod = $this->input->post('id_prod');
                        $id_kat = $this->input->post('id_kat');
                        $slug = $this->input->post('slug');
                                                
						$this->session->set_flashdata('message_type','Exceed the maximum limit orders, please confirm further');
						redirect('produk/view/'.$id_brand.'/'.$id_kat.'/'.$id_prod.'/'.$slug,'refresh');
					}
					else
					{
						$date = date("Y-m-d h:i:s");
						//addToCart($session_id,$produk_id,$harga,$disc,$jml,$size_id,$date){
						$this->Order_model->addToCart($session_id,$id_prod,$harga,$disc,$jml,$size_id,$date);
						
						$id_brand = $this->input->post('id_brand');
						$id_prod = $this->input->post('id_prod');
						$id_kat = $this->input->post('id_kat');
						$slug = $this->input->post('slug');
						$this->session->set_flashdata('message_type4','The product was added to your cart');
						redirect('produk/view/'.$id_brand.'/'.$id_kat.'/'. $id_prod.'/'.$slug,'refresh');
					}
				}
			}
			else 
			{
				$data['ses_id'] = $this->session->userdata('session_id');
				$data['title'] = 'Expired Session';
				$data['main_view'] = 'empty_ses';
				$this->load->view('index',$data);
			}
		}
	}

	
	function add_cart_fast(){

		$this->form_validation->set_rules('jml', 'Jumlah', 'required');
		
		if ($this->form_validation->run() == FALSE)
		{
			$id_brand = $this->input->post('id_brand');
                        $id_prod = $this->input->post('id_prod');
                        $id_kat = $this->input->post('id_kat');
                        $slug = $this->input->post('slug');
			redirect('produk/view/'.$id_brand.'/'.$id_kat.'/'.$id_prod.'/'.$slug,'refresh');
		}
		else
		{
			
			$session_id = $this->session->userdata('session_id');
			$id_brand = $this->input->post('id_brand');
                        $id_prod = $this->input->post('id_prod');
                        $id_kat = $this->input->post('id_kat');
                        $slug = $this->input->post('slug');
			
			
			if((!empty($id_prod))&& (!empty($session_id))) {
				$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
				$this->form_validation->set_rules('jml', 'Jumlah', 'trim|required');
				if ($this->form_validation->run() == FALSE) {
                                    $id_brand = $this->input->post('id_brand');
                                    $id_prod = $this->input->post('id_prod');
                                    $id_kat = $this->input->post('id_kat');
                                    $slug = $this->input->post('slug');
                                    redirect('produk/view/'.$id_brand.'/'.$id_kat.'/'.$id_prod.'/'.$slug,'refresh');
				}
				else 
				{
					$jml = mysql_escape_string($this->input->post('jml'));
                    $size_id = mysql_escape_string($this->input->post('size_produk_id'));
					$prod = $this->Produk_model->getProductById($id_prod,$size_id);
					$jml_stok = $prod->jml_item;
					$harga = $prod->harga;
					$disc = $prod->persen_diskon;
					$itung = $jml_stok - $jml;
					if ($itung<0)
					{
                            $id_brand = $this->input->post('id_brand');
                            $id_prod = $this->input->post('id_prod');
                            $id_kat = $this->input->post('id_kat');
                            $slug = $this->input->post('slug');
							$this->session->set_flashdata('message_type','Exceed the maximum limit orders, please confirm further');
							redirect('produk/view/'.$id_brand.'/'.$id_kat.'/'.$id_prod.'/'.$slug,'refresh');
					}
					else
					{

						$date = date("Y-m-d h:i:s");
						//addToCart($session_id,$produk_id,$harga,$disc,$jml,$size_id,$date){
						$this->Order_model->addToCart($session_id,$id_prod,$harga,$disc,$jml,$size_id,$date);
						
						$id_brand = $this->input->post('id_brand');
						$id_prod = $this->input->post('id_prod');
						$id_kat = $this->input->post('id_kat');
						$slug = $this->input->post('slug');
						$this->session->set_flashdata('message_type4','The product was added to your cart');
						redirect('produk/kategori/'.$id_brand.'/'.$id_kat.'/'.$slug,'refresh');
					}
				}
			}
			else 
			{
				$data['ses_id'] = $this->session->userdata('session_id');
				$data['title'] = 'Expired Session';
				$data['main_view'] = 'empty_ses';
				$this->load->view('index',$data);
			}
		}
	}

	function edit_item($session_id=FALSE,$produk_id=FALSE,$temp_size=FALSE){
                //echo $temp_size;
		$this->db->where('session_id',$session_id);
		$query = $this->db->get('tb_temp_cart');
		$custLog = $query->result_array();
		$num_cart = $query->num_rows();
		if($num_cart>0) {
			$data['num_cart'] = $this->Order_model->getCart($session_id,$produk_id,TRUE,$temp_size);
			if(($data['num_cart'])>0) {
				$data['ses_id'] = $this->session->userdata('session_id');
				$data['prod_cat'] = $this->Produk_model->getKatProduk('all',FALSE,FALSE,FALSE);
				$data['cumb'] = anchor('produk','<strong>Home</strong>').' &raquo; '.anchor('order','<strong>Cart</strong>').' &raquo; Edit Cart';	
				$sql =$this->db->query("SELECT SUM(temp_jml) as tot_temp,SUM(temp_subtotal) as tot_subtotal
							FROM tb_temp_cart
							WHERE session_id = '$session_id'");
				
				$data['total']=$sql->row('tot_subtotal');
				$data['cart'] = $this->Order_model->getCart($session_id,$produk_id,FALSE,$temp_size);
				
				
				// QUERY GET FAVORITE PRODUK
		
				$qr_fav = $this->db->query('
					SELECT 
					pr.produk_id,
					pr.nama_produk,
					pr.prod_brand_id,
					pr.harga,
					pr.persen_diskon,
					pr.prod_kat_id,
					pr.deskripsi,
					img.produk_img_thumb,
					count(pr.produk_id) AS count_pr
					FROM tb_wishlist ws
					INNER JOIN tb_produk pr ON pr.produk_id = ws.produk_id
					INNER JOIN tb_image_produk img ON img.image_produk_id = ws.produk_id
					WHERE img.look = 1
					GROUP BY pr.produk_id
					ORDER BY count_pr DESC LIMIT 4
				');
				$data['arr_produk_fav'] = $qr_fav->result_array();
				
				
				$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
				$this->form_validation->set_rules('jml', 'Jumlah', 'trim|required');
				$jml = mysql_escape_string($this->input->post('jml'));
				if ($this->form_validation->run() == FALSE) {
					$data['page'] = 'common';
					$data['msg']='no_msg';
					$data['product'] = $this->Produk_model->getProduk('all',FALSE,FALSE,FALSE);
					$data['main_view'] = '/slak/order/order_cart_edit';
					$this->load->view('/slak/index',$data);
				}
				else 
				{
					$jml = mysql_escape_string($this->input->post('jml'));
                    $size_id = mysql_escape_string($this->input->post('size_produk_id'));
					$prod = $this->Produk_model->getProductById($produk_id,$temp_size);
					$jml_stok = $prod->jml_item;
					$harga = $prod->harga;
					$disc = $prod->persen_diskon;
					$itung = $jml_stok - $jml;

					if ($itung<0)
					{
						$data['page'] = 'common';
						$data['msg'] = 'Exceed the maximum limit orders, please confirm further';
						$data['product'] = $this->Produk_model->getProduk('all',FALSE,FALSE,FALSE);
						$data['main_view'] = '/slak/order/order_cart_edit';
						$this->load->view('/slak/index',$data);
					}
					else
					{
						$date = date("Y-m-d h:i:s");
						if( $disc != 0):
							$subtotal = $jml * getPriceDiskon($prod->harga,$prod->persen_diskon);
							$this->Order_model->editCart($session_id,$produk_id,$harga,$disc,$jml,$size_id,$subtotal);
						else:
							$subtotal = $jml * $prod->harga;
							$this->Order_model->editCart($session_id,$produk_id,$harga,$disc,$jml,$size_id,$subtotal);
						endif;

						redirect('order/','refresh');
					}
				}
			}
			else {
				redirect('order/','refresh');
			}
		}
		else {
			$data['ses_id'] = $this->session->userdata('session_id');
			$data['title'] = 'Expired Session';
			$data['prod_cat'] = $this->Produk_model->getKatProduk('all',FALSE,FALSE,FALSE);
			//$data['vendor'] = $this->Produk_model->getVendor('all',FALSE,FALSE,FALSE);
			$data['main_view'] = 'empty_ses';
			$this->load->view('index',$data);
		}
	}

	function deleteItem($session_id=FALSE,$produk_id=FALSE,$size_prod_id = FALSE){
		$this->db->where('session_id',$session_id);
		$query = $this->db->get('tb_temp_cart');
		$custLog = $query->result_array();
		$num_cart = $query->num_rows();
		if(($num_cart>0)&&(!empty($produk_id))) {
			$this->Order_model->deleteCart($session_id,$produk_id,$size_prod_id);
			redirect('order/','refresh');
		}
		else {
			$data['ses_id'] = $this->session->userdata('session_id');
			$data['title'] = 'Expired Session';
			$data['prod_cat'] = $this->Produk_model->getKatProduk('all',FALSE,FALSE,FALSE);
			//$data['vendor'] = $this->Produk_model->getVendor('all',FALSE,FALSE,FALSE);
			$data['main_view'] = 'empty_ses';
			$this->load->view('index',$data);
		}
	}
	
	
		
	
	function add_wishlist(){
		if(memLogin()>0)// cek login tidak??
		{
			$session_id = $this->session->userdata('session_id');
			$this->db->where('session_id',$session_id);
			$query = $this->db->get('tb_temp_login');
			$temp = $query->row();
			$mem_id = $temp->temp_mem_id;
			$date = date("Y-m-d");
			
			// cek on wishlist
			$this->db->where('member_id',$mem_id);
			$this->db->where('produk_id',$this->input->post('id_prod'));
			$qr = $this->db->get('tb_wishlist');
			
			if($qr->num_rows() == 0):
				$data = array(
					'member_id' => $this->session->userdata('member_id'),
					'produk_id' => $this->input->post('id_prod'),
					//'keterangan' => '',
					'date_added' => $date
					);
				$this->Order_model->addWishlist($data);
				
				$id_brand = $this->input->post('id_brand');
                $id_prod = $this->input->post('id_prod');
                $id_kat = $this->input->post('id_kat');
                $slug = $this->input->post('slug');
				
				$this->session->set_flashdata('message_type2','The product is add to your Wishlist');
				redirect('produk/view/'.$id_brand.'/'.$id_kat.'/'. $id_prod.'/'.$slug,'refresh');
			else:
			
				$id_brand = $this->input->post('id_brand');
                $id_prod = $this->input->post('id_prod');
                $id_kat = $this->input->post('id_kat');
                $slug = $this->input->post('slug');
				$this->session->set_flashdata('message_type2','The product is already on your Wishlist, Please check in your account');
				redirect('produk/view/'.$id_brand.'/'.$id_kat.'/'. $id_prod.'/'.$slug,'refresh');
			endif;
		}
		else
		{
			
							
			/*$data['ses_id'] = $this->session->userdata('session_id');
			$data['title'] = 'Expired Session';
			$data['main_view'] = 'empty_ses';
			$this->load->view('index',$data);
			*/
			redirect('login','refresh');
							
		}
		
	}
	
		
	function ajax_add_cart_fast(){
	
		$session_id = $this->session->userdata('session_id');

		// THE URL url=url+pr_id+"_"+kat_id+"_"+brand_id+"_"+size_id+"_"+prod_value+"_"+slug;
		//$get_url = $this->uri->segment(3);

		//$arr_url = explode("_",$get_url);

		//$id_prod = $arr_url[0];
		//$id_kat = $arr_url[1];
		//$id_brand = $arr_url[2];
		//$size_id = $arr_url[3];
		//$jml = $arr_url[4];
		//$slug = $arr_url[5];
		
		$id_prod = $_POST['prod_id'];
		$id_kat = $_POST['kat_id'];
		$id_brand = $_POST['brand_id'];
		$size_id = $_POST['size_id'];
		$jml = $_POST['prod_val'];
		$slug = $_POST['slug'];

		

		$prod = $this->Produk_model->getProductById($id_prod,$size_id);
		$jml_stok = $prod->jml_item;
		$harga = $prod->harga;
		$disc = $prod->persen_diskon;
		$itung = $jml_stok - $jml;

		$date = date("Y-m-d h:i:s");
		$this->Order_model->addToCart($session_id,$id_prod,$harga,$disc,$jml,$size_id,$date);

		
		// FROM HELPER
		echo myCart();
		
		
		
	}

	function checkout(){
		$session_id = $this->session->userdata('session_id');
		$this->db->where('session_id',$session_id);
		$qr = $this->db->get('tb_temp_cart');
		if($qr->num_rows() !=0)// cek temp cart dg session id kosong bolong tidak??
		{
			if(memLogin()>0)// cek login tidak??
			{
				if(($this->input->post('new_alamat_kirim')=="") && ($this->input->post('new_prov_id')==0) && 
				($this->input->post('new_kab_id')==0) && ($this->input->post('new_kodepos')=="") && ($this->input->post('new_cty')=="") &&
				($this->input->post('id_log')==0) && ($this->input->post('new_id_bank')==0) )// cek alamat baru diisi tidak??
				{

					$this->form_validation->set_rules('bank_id', 'Rekening Bank', 'required');
					//$this->form_validation->set_rules('logistik_id', 'Logistik', 'required');
					$this->form_validation->set_rules('terms', 'Terms and Condition', 'required');
					
					// cek member yg login sesuai session di tb temp login
					$this->db->where('session_id',$session_id);
					$query = $this->db->get('tb_temp_login');
					$temp = $query->row();
					$mem_id = $temp->temp_mem_id;
					if ($this->form_validation->run() == FALSE) 
						{
							$data['acc'] = $this->Member_model->getDataLogin($session_id,$mem_id);//hehe salah satu manfaat query di atas
							$data['ses_id'] = $this->session->userdata('session_id');
							$data['cumb'] = anchor('produk','<strong>Home</strong>').' &raquo; '.anchor('order','<strong>Cart</strong>').' &raquo; Check Out Member';
							$data['title'] = 'Check Out Member ';
							$data['prod_cat'] = $this->Produk_model->getKatProduk('all',FALSE,FALSE,FALSE);
							$data['page'] = 'common';
							$data['main_view'] = 'slak/order/checkout_member';
							$this->load->view('slak/index',$data);
						}
					else 
						{
						// cek temp_cart nya
						$this->data['num_cart'] = $this->Order_model->getCart($session_id,FALSE,FALSE);
						if(($this->data['num_cart']) > 0)
						{		
							$mem_login = $this->Member_model->getDataLogin($session_id,$mem_id);
									
							$sql =$this->db->query("SELECT SUM(temp_jml) as tot_temp,SUM(temp_subtotal) as tot_subtotal
											FROM tb_temp_cart
											WHERE session_id = '$session_id'");
								
							$total=$sql->row('tot_subtotal');
									
							/// get max order_id for code order
							$this->db->select_max('order_id');
							$query = $this->db->get('tb_order');
							$result = $query->row_array();
							$last = $result['order_id'];
									
							$d = explode(":",date('Y:m:d'));
					
							$date_code = $d[2].''.$d[1];// get 
									
							$order_code = $last + 1;
							
							
							
				
							$data = array(
											'order_member_id' => $mem_login->member_id,
											'order_bank_id' => $this->input->post('bank_id'),
											'alamat_kirim' => $mem_login->alamat,
											'order_prov_id' => $mem_login->mem_prov_id,
											'order_kab_id' => $mem_login->mem_kab_id,
											'kodepos_kirim' => $mem_login->kodepos,
											'lokasi' => 1,// INSIDE TOWN
											'total' => $total,
											'order_status' => 'neworder',
											'order_code' => ("INV".$date_code."ID".$order_code),
											'order_date' => date("Y-m-d h:i:s"),
											'en_code' => md5("INV".$date_code."ID".$order_code)
											);  
							$this->Order_model->addOrder($data);
						
	
							//get max id_order for insert tb_detal order and bwt ucapan selamatt
							
							$last_order_id = $this->db->insert_id();
									
							//get sub total
							$this->db->where('session_id',$session_id);
							$query = $this->db->get('tb_temp_cart');
							$cart = $query->result_array();
                                                     
							//insert detail order
								foreach($cart as $cart)
								{
									$data = array(
												'order_id' => $last_order_id,
												'produk_id' => $cart['temp_produk_id'],
                                                'prod_size_id' => $cart['temp_size_produk_id'],
												'harga' => $cart['temp_harga'],
												'persen_diskon' => $cart['temp_persen_diskon'],
												'session_id' => $session_id,
												'det_jml' => $cart['temp_jml'],
												'det_subtotal' => $cart['temp_subtotal']
												);
									$this->Order_model->addOrderDetail($data);
								}
									
							//minus jml_stok di produknya yahh lmyan lah agak janggal di last_order_id nya
                                $this->db->where('order_id',$last_order_id);
                                $query = $this->db->get('tb_order_detail');
                                $cr = $query->result_array();

								foreach ($cr as $cr)
								{
									// get stok awal produk
									$this->db->where('ms_size_id',$cr['prod_size_id']);
                                    $this->db->where('produk_id',$cr['produk_id']);
									$query = $this->db->get('tb_size_produk');
									$qr1 = $query->row();	
										
									$qt1 = $qr1->jml_item;
										
									//get jml produk yg di order
									$this->db->where('temp_produk_id',$cr['produk_id']);
                                    $this->db->where('temp_size_produk_id',$cr['prod_size_id']);
									$query = $this->db->get('tb_temp_cart');
									$qr2 = $query->row();
										
									$qt2 = $qr2->temp_jml;
										// lets minus the produk
									$qt3 = $qt1-$qt2;
										
									$this->db->set('jml_item',$qt3);
			
									// jika stok 0 langsung set ke Tidak
									
									$this->db->where('produk_id',$cr['produk_id']);
                                    $this->db->where('size_produk_id',$cr['prod_size_id']);
									$this->db->update('tb_size_produk');
								}
									
								
								// SEND MAIL
								
								//SEND MAIL TO MEMBER
								
								$en_code = (md5("INV".$date_code."ID".$order_code));
								
								$order = $this->Order_model->getOrderBy('by_code',FALSE,$en_code);

								$config['mailtype'] = 'text';
								$this->email->initialize($config);

								$this->email->from($this->config->item('mail@slackerscompany.com'), $this->config->item('Slackers Company')); // config email pengirim
								$this->email->to($form_data['email']);
								$this->email->subject("Confirmation Order");

								$f=fopen("./email_message/checkout_message.html","r");
								$message=fread($f,filesize("./email_message/checkout_message.html"));
								$message=str_replace("[NAME]",$order->nama,$message);
								$message=str_replace("[EMAIL]",$order->email,$message);
								$message=str_replace("[DATE]",formatDate($order->order_date,'short1'),$message);
								$message=str_replace("[INV_NO]",$order->order_code,$message);
								$message=str_replace("[STATUS]",$order->order_status,$message);
								$message=str_replace("[TOTAL]",'IDR '.$total,$message);
								$message=str_replace("[REKENING]",$order->nama_rek.' - '.$order->nama_bank.' - '.$order->no_rek,$message);

								$message=str_replace("[LINK]",base_url().'order/cetak/'.$en_code,$message);
								
								$this->email->message($message);
								$this->email->send();
								echo $this->email->print_debugger();
								
								
								
								
								
								$this->Order_model->deleteTempCart($session_id);
									
								$data['ses_id'] = $this->session->userdata('session_id');
								$data['title'] = 'Finish';
								$data['cumb'] = anchor('home','<strong>Home</strong>').' &raquo;  Order Finish';	
								$data['order'] = $this->Order_model->getOrderBy('by_id',$last_order_id,FALSE);
								$data['det_order'] = $this->Order_model->getOrderDetailById($last_order_id);
								$data['prod_cat'] = $this->Produk_model->getKatProduk('all',FALSE,FALSE,FALSE);
								$data['page'] = 'common';
								$data['key_order'] = md5($data['order']->order_code);
								$data['main_view'] = 'slak/order/finish';
								$this->load->view('slak/index',$data);
						}
						else
						{
							
							redirect('home','refresh');
						}	
					}
				}
				else //jika alamat diisi baru
				{
					// cek member yg login sesuai session di tb temp login
					$this->db->where('session_id',$session_id);
					$query = $this->db->get('tb_temp_login');
					$temp = $query->row();
					$mem_id = $temp->temp_mem_id;
					// cek temp_cart nya
					$this->data['num_cart'] = $this->Order_model->getCart($session_id,FALSE,FALSE);
					if(($this->data['num_cart']) > 0)
					{		
						$mem_login = $this->Member_model->getDataLogin($session_id,$mem_id);
						// get logistik id
						$getLog = explode("-",$this->input->post('logistik_id'));
						$idLog = $getLog[1];
									
						$this->db->where('logistik_id',$idLog);
						$query = $this->db->get('tb_logistik');
						$log = $query->row();
									
						// get itungan logistik
						$log_biaya = $log->log_biaya;
								
						$sql =$this->db->query("SELECT SUM(temp_jml) as tot_temp,SUM(temp_subtotal) as tot_subtotal
											FROM tb_temp_cart
											WHERE session_id = '$session_id'");
								
						$total=$sql->row('tot_subtotal')+$log_biaya;
									
						/// get max order_id for code order
						$this->db->select_max('order_id');
						$query = $this->db->get('tb_order');
						$result = $query->row_array();
						$last = $result['order_id'];
									
						$d = explode(":",date('Y:m:d'));
					
						$date_code = $d[2].''.$d[1];// get 
									
						$order_code = $last + 1;
		
							$data = array(
										'order_member_id' => $mem_login->member_id,
										'order_bank_id' => $this->input->post('bank_id'),
										'order_logistik_kirim_id' => 1,
										'alamat_kirim' => $this->input->post('new_alamat_kirim'),
										'order_prov_id' => $this->input->post('prov_id'),
										'order_kab_id' => $this->input->post('kab_id'),
										'kodepos_kirim' => $this->input->post('new_kodepos'),
										'biaya_logistik' => $log_biaya,
										'total' => $total,
										'lokasi' => 2,// OUTSIDE TOWN
										'order_status' => 'neworder',
										'order_code' => ("INV".$date_code."ID".$order_code),
										'order_date' => date("Y-m-d h:i:s"),
										'date_sk' => $row2['time_id'],
										'en_code' => md5("INV".$date_code."ID".$order_code)
										);  
							$this->Order_model->addOrder($data);

									
						//get max id_order for insert tb_detal order and bwt ucapan selamatt
						$this->db->select_max('order_id');
						$query = $this->db->get('tb_order');
						$result_last_order_id = $query->row_array();
						$last_order_id = $this->db->insert_id();
									
						//get sub total
						$this->db->where('session_id',$session_id);
						$query = $this->db->get('tb_temp_cart');
						$cart = $query->result_array();
						//insert detail order
						foreach($cart as $cart)
						{
							$data = array(
										'order_id' => $last_order_id,
										'produk_id' => $cart['temp_produk_id'],
										'harga' => $cart['temp_harga'],
										'session_id' => $session_id,
										'det_jml' => $cart['temp_jml'],
										'det_subtotal' => $cart['temp_subtotal']
										);
							$this->Order_model->addOrderDetail($data);
						}
									
						//minus jml_stok di produknya yahh lmyan lah agak janggal di last_order_id nya
						$this->db->where('order_id',$last_order_id);
						$query = $this->db->get('tb_order_detail');
						$cr = $query->result_array();

						foreach ($cr as $cr)
						{
							// get stok awal produk
							$this->db->where('produk_id',$cr['produk_id']);
							$query = $this->db->get('tb_produk');
							$qr1 = $query->row();	
										
							$qt1 = $qr1->jml_stok;
										
							//get jml produk yg di order
							$this->db->where('temp_produk_id',$cr['produk_id']);
							$query = $this->db->get('tb_temp_cart');
							$qr2 = $query->row();
										
							$qt2 = $qr2->temp_jml;
										// lets minus the produk
							$qt3 = $qt1-$qt2;
										
							$this->db->set('jml_stok',$qt3);
										
							// jika stok 0 langsung set ke Tidak
							if($qt3==0){
							$this->db->set('tersedia','Tidak');
							}
							$this->db->where('produk_id',$cr['produk_id']);
							$this->db->update('tb_produk');
						}
									
						// hapus temp cartnya biar ga numpukkkkkkkkk
						$this->Order_model->deleteTempCart($session_id);
	
						$data['ses_id'] = $this->session->userdata('session_id');
						$data['title'] = 'Order Finish';
						$data['cumb'] = anchor('home','<strong>Home</strong>').' &raquo;  Order Finish';	
						$data['order'] = $this->Order_model->getOrderBy('by_id',$last_order_id,FALSE);
						$data['det_order'] = $this->Order_model->getOrderDetailById($last_order_id);
						$data['prod_cat'] = $this->Produk_model->getKatProduk('all',FALSE,FALSE,FALSE);
						$data['key_order'] = md5($data['order']->order_code);
						$data['page'] = 'common';
						$data['main_view'] = 'slak/order/finish';
						$this->load->view('index',$data);
					}
					else
					{
						redirect('home','refresh');
					}
				}
			}
			else
			{
				$data['page'] = 'common';
				$data['ses_id'] = $this->session->userdata('session_id');
				$data['title'] = 'Check Out Step 1';
				$data['cumb'] = anchor('home','<strong>Home</strong>').' &raquo; '.anchor('order','<strong>Cart</strong>').' &raquo; Check Out Step 1';	
				$data['prod_cat'] = $this->Produk_model->getKatProduk('all',FALSE,FALSE,FALSE);
				$data['main_view'] = 'slak/order/checkout_first';
				$this->load->view('slak/index',$data);
			}
		}
		else
		{
			redirect('home','refresh');
		}
	}

	function doLogin()
	{
		$this->form_validation->set_rules('email', 'Email', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');

		if ($this->form_validation->run() == FALSE):
			$data['ses_id'] = $this->session->userdata('session_id');
			$data['title'] = 'Registrasi';
			$data['cumb'] = anchor('home','<strong>Home</strong>').' &raquo; Register';	
			$data['prod_cat'] = $this->Produk_model->getKatProduk('all',FALSE,FALSE,FALSE);
			//$data['vendor'] = $this->Produk_model->getVendor('all',FALSE,FALSE,FALSE);
			$data['page'] = 'common';
			$data['main_view'] = 'slak/login';
			$this->load->view('slak/index',$data);
		else:
			$email = $this->input->post('email');
			$password = md5($this->input->post('password'));
			$this->db->where('email',$email);
			$this->db->where('password',$password);
			$this->db->where('status',1);
			$res = $this->db->get('tb_member')->result();

			if (count($res) > 0):
				$session_id = $this->session->userdata('session_id');
				$cust_id = $res[0]->member_id;
				$email = $res[0]->email;
				$pass = $res[0]->password;
				
				$data = array('session_id' => $session_id,
							  'temp_mem_id' => $cust_id,
							  'temp_email' => $email,
							  'temp_password' => $pass
							  );  
				$this->Member_model->addTempLogin($data);
				$this->session->set_userdata('nama',$res[0]->nama);
				$this->session->set_userdata('email',$res[0]->email);
				redirect('order/checkout','refresh');
			else:
				redirect('login');
			endif;
		endif;
	}
	
	
	
	function header_top($en_code)
	{
		$this->load->library('cezpdf');
		//cquery
		$order = $this->Order_model->getOrderBy('by_code',FALSE,$en_code);
		
		// nama toko
		$this->cezpdf->ezText('Slackers Distro Company', 18, array('justification' => 'right'));
		$this->cezpdf->ezSetDy(-50,'makeSpace');
		
		
		// data member
		$this->cezpdf->ezText('INVOICE NO : '.$order->order_code, 14, array('justification' => 'left'));
		$this->cezpdf->ezText('Tanggal : '.formatDate($order->order_date,'short1'), 14, array('justification' => 'left'));
		$this->cezpdf->ezText('Status : '.$order->order_status, 14, array('justification' => 'left'));
	
		$this->cezpdf->ezSetDy(-10,'makeSpace');
		
		$this->cezpdf->ezText($order->nama, 12, array('justification' => 'left'));
		$this->cezpdf->ezText($order->alamat.','.$order->kota.','.$order->nama_kabupaten, 12, array('justification' => 'left'));
		$this->cezpdf->ezText($order->nama_provinsi.','.$order->kodepos, 12, array('justification' => 'left'));
		$this->cezpdf->ezText($order->alamat_kirim, 12, array('justification' => 'left'));
		
		$this->cezpdf->ezSetDy(-10,'makeSpace');
		
		$this->cezpdf->ezText('Rekening : '.$order->nama_rek.' - '.$order->nama_bank.' - '.$order->no_rek, 12, array('justification' => 'left'));
		
		
	}
	function cetak()
	{
	
		$en_code = $this->uri->segment(3);
		
		$this->load->library('cezpdf');
	
		$order = $this->Order_model->getOrderBy('by_code',FALSE,$en_code);
		
		$order_id = $order->order_id;
		$arr_det_order = $this->Order_model->getOrderDetailById($order_id);
	
		$hdkolom = array (
			'nama_produk' => '<b>Item</b>',
			'size' => '<b>Size</b>',
			'harga' => '<b>Price</b>',
			'det_jml' => '<b>Total</b>',
			'det_subtotal' => '<b>Sub Total</b>'
			
			);
		
		
		foreach ($arr_det_order as $row)
		{
			if($row['persen_diskon'] != 0):
				$data[] = array (
				'nama_produk' => $row['nama_produk'],
				'size' => $row['kode_size'],
				'harga' => formatHarga(getPriceDiskon($row['harga'],$row['persen_diskon']), 'lengkap'),
				'det_jml' => $row['det_jml'],
				'det_subtotal' => formatHarga($row['det_subtotal'],'lengkap')
				);
			else:
				$data[] = array (
				'nama_produk' => $row['nama_produk'],
				'size' => $row['kode_size'],
				'harga' => formatHarga($row['harga'], 'lengkap'),
				'det_jml' => $row['det_jml'],
				'det_subtotal' => formatHarga($row['det_subtotal'],'lengkap')
				);
			endif;
			
		}
		
		//$data[] = array (
		//		'nama_produk' => 'Jasa Kirim',
		//		'harga' => '',
		//		'det_jml' => '',
		//		'det_subtotal' => formatHarga($order->log_biaya,'lengkap')
		//		);
		
		$data[] = array (
				'nama_produk' => '',
				'size' => '',
				'harga' => '',
				'det_jml' => 'TOTAL',
				'det_subtotal' => formatHarga($order->total,'lengkap')
				);
		

		$this->header_top($en_code);
		$this->cezpdf->ezSetDy(-20,'makeSpace');
		$this->cezpdf->ezTable($data,$hdkolom,'Detail Order',array('shaded'=>0,'width'=>500));
		$this->cezpdf->setLineStyle(1);
		$this->cezpdf->ezStream();
		
	
	
	}
	
	
	function ajax_insertKode()
	{
		$kode = $this->uri->segment(3);
		
		
		echo '<input class="contact_input" readonly="readonly" style="width:50px" name="logistik_id" type="text" id="number" value="'.$kode.'"/>';	
		
	}
	
						
	
}

/* End of file order.php */
/* Location: ./system/application/controllers/order.php */